const { get_file_list, read_cfg, get_fst_file } = require("../utils/file_tool");
const {
    whisper,
    info,
    warn,
    success,
    vital,
    setLastExecFile,
    getLastError,
} = require("../utils/log_tool");
const { parse } = require("../utils/parse_tool");
const { doRequest } = require("../utils/request_tool");
const { toArray } = require("../utils/transform_tool");
const { BaseCommand } = require("./base");

class ExecFromFileCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        const srcs = toArray(data.src);
        for (let i = 0; i < srcs.length; i++) {
            let src = srcs[i];
            const isRemote = /^https?:\/\//.test(src);
            if (!isRemote) {
                src = get_fst_file(src);
            }
            if (!src) {
                throw `配置文件未找到 ${srcs[i]}`;
            }
            if (!data.force && this.globalData.executed_cfg.includes(src)) {
                info(`不执行重复配置 ${src}`);
                continue;
            }
            info(`执行配置文件 ${src}`);
            this.globalData.executed_cfg.push(src);
            setLastExecFile(src);
            let cfg;
            if (isRemote) {
                const content = await doRequest({ src, quiet: true });
                if (getLastError()) {
                    return;
                }
                cfg = await parse(content, "yml");
            } else {
                cfg = await read_cfg(src, data.type);
            }
            await this.exec(cfg, this.depth + 1);
        }
    }
}

module.exports = {
    ExecFromFileCommand,
};
